/**
 * 
 */
package com.chocolatefordogs.writersnb.core.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.plaf.basic.BasicButtonUI;

/**
 * Component used to create a "closeable" tab, using a
 * label to display the tab title and a button to close
 * the tab.  Inspired by/shamelessly copied from 
 * http://download.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
 *  
 * @author Matthew Cory
 */
public final class CloseableTabComponent extends JPanel {
	
	public CloseableTabComponent(final JTabbedPane pane) {
		super();
		if (pane == null) {
			throw new NullPointerException("Pane must be provided.");
		}
		
		this.pane = pane;
	
		setOpaque(false);
		
		label = new JLabel() {
			@Override
			public String getText() {
				final int idx = pane.indexOfTabComponent(CloseableTabComponent.this);
				if (idx != -1) {
					return pane.getTitleAt(idx);
				}
				
				// default to whatever this thing decides to
				// do on it's own.  Probably nothing, but what the hell...
				return super.getText();
			}
		};
		add(label);
		
		closeButton = new CloseButton();
		closeButton.setText("x");
		add(closeButton);
	}
	
	private final class CloseButton extends JButton implements ActionListener {

		public CloseButton() {
			super();
			addActionListener(this);
			
			setUI(new BasicButtonUI());
			setOpaque(false);
			setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
			setPreferredSize(new Dimension(15, 15));
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			final int idx = pane.indexOfTabComponent(CloseableTabComponent.this);
			if (idx != -1) {
				pane.remove(idx);
			}
		}
	}
	
	private final JTabbedPane pane;
	private final JLabel label;
	private final JButton closeButton;
}
